<?php

namespace app\common\payplug;

use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;

class AliPay
{
    /**
     * app支付
     *
     * @param [type] $subject    商品描述
     * @param [type] $outTradeNo 订单编号
     * @param [type] $totalAmount   支付金额
     * @param [type] $totalAmount 回调地址
     * @return void 唤起支付字符串
     */
    public function app($subject, $outTradeNo, $totalAmount, $NotifyUrl)
    {
        Factory::setOptions($this->getOptions());
        try {
            $result = Factory::payment()->app()
                ->asyncNotify(config('app.app_host') . $NotifyUrl)
                ->pay($subject, $outTradeNo, $totalAmount);
            $responseChecker = new ResponseChecker();
            if ($responseChecker->success($result)) {
                return ['state' => 1, 'body' => $result->body];
            } else {
                return ['state' => 0, 'body' => "调用失败，原因：" . $result->msg . "，" . $result->subMsg . PHP_EOL];
            }
        } catch (\Exception $e) {
            return ['state' => 0, 'body' => "调用失败，" . $e->getMessage() . PHP_EOL];
        }
    }

    /**
     * 用户扫商家二维码进行支付
     *
     * @param [type] $subject    商品描述
     * @param [type] $outTradeNo 订单编号
     * @param [type] $totalAmount   支付金额
     * @param [type] $totalAmount 回调地址
     * @return void 用于生成支付二维码的链接地址
     */
    public function scan_qrcode($subject, $outTradeNo, $totalAmount, $NotifyUrl)
    {
        Factory::setOptions($this->getOptions());
        try {
            $result = Factory::payment()->FaceToFace()
                ->asyncNotify(config('app.app_host') . $NotifyUrl)
                ->precreate($subject, $outTradeNo, $totalAmount);
            $responseChecker = new ResponseChecker();
            if ($responseChecker->success($result)) {
                return ['state' => 1, 'body' => $result->qrCode];
            } else {
                return ['state' => 0, 'body' => "调用失败，原因：" . $result->msg . "，" . $result->subMsg . PHP_EOL];
            }
        } catch (\Exception $e) {
            return ['state' => 0, 'body' => "调用失败，" . $e->getMessage() . PHP_EOL];
        }
        // $result = Factory::payment()->FaceToFace()->precreate("测试商品", date('YmdHis'), "0.01");
    }

    /**
     * 退款
     *
     * @param [type] $outTradeNo  订单编号
     * @param [type] $outRequestNo  退款号
     * @param [type] $refundAmount  退款金额
     * @return void
     */
    public function refund($outTradeNo, $outRequestNo, $refundAmount)
    {
        Factory::setOptions($this->getOptions());
        try {
            $result = Factory::payment()->Common()->refund($outTradeNo, $outRequestNo, $refundAmount);
            $responseChecker = new ResponseChecker();
            if ($responseChecker->success($result)) {
                return ['state' => 1, 'body' => $result->msg];
            } else {
                return ['state' => 0, 'body' => "调用失败，原因：" . $result->msg . "，" . $result->subMsg . PHP_EOL];
            }
        } catch (\Exception $e) {
            return ['state' => 0, 'body' => "调用失败，" . $e->getMessage() . PHP_EOL];
        }
    }

    /**
     * 支付回调验证
     *
     * @param [type] $param  接收到的通知参数数组
     * @return void
     */
    public function verifyNotify($param)
    {
        Factory::setOptions($this->getOptions());
        return Factory::payment()->common()->verifyNotify($param);
    }


    public function getOptions()
    {
        $config = [
            'ali_app_id' => '2021004128682862',
            'ali_alipay_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkhE+1jVBh/7Cy8CgnUtMxCt/laCSDpnkFLtbF+rOwrEeEg10pkPhUHIz5kQeWCV7ICPP3GQ6hqfurtRTKg4ehcjnq5zRx6PQa9GDRklOUWe3htXFpq02KoaYJEdP/KTmQZD9Ar/yW2N6Z67A8te4390QztQlKy+k/hrI6AHlYoHwJmwtvz3YvUlkufnYRQFbcg5ows/gWEDNmdrhOPjFOoJteZDtYY947nUf3sORjPblY7NOSRCOLOsXUKmjVWpfvDyvZw6Y7pRMLhSRFTCiXD93GS7RJ18h0jCB29NT9/3pcN4GlmEzmuo4k9mBB0LBbmbGL+QEV4j9fzYwuYW/XQIDAQAB',
            'ali_merchant_private_key' => 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCSET7WNUGH/sLLwKCdS0zEK3+VoJIOmeQUu1sX6s7CsR4SDXSmQ+FQcjPmRB5YJXsgI8/cZDqGp+6u1FMqDh6FyOernNHHo9Br0YN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jtPXsnck9/2alaocR0xuaMCco2C/7ElcwSrWUKRc2NcYRTcHyU0zABNjCBAoGAYx3irZlrAGbR+Ro13csV2sER1cgw91R80q9ytcn54KjLLw3Ocb8cBtTu9BbQHUuN1KUOg2PoF3GiANHcqSomCyODZv6GJ2xPYxxLbtw2sA8pwK/FcPXeiCNrOxeiDX7mc3t5l3QZ/2rmywSY5wLI8FcdVHdhvo3+n6XsN3XZ4QECgYEAmW+7sQsGY6R6r7ONDxnnSSuhTBXBm0780xbPzq1gtSJQo5eydOyW+2e/2pL8zpatv+euGgXB54PCKl/WpF9PKGccj29HFPrzniazgsyhPRoqr1jHrSuVPkcNWGIClOvocurXU+wbc3MWUXEbJLze/f4HxMQayw5G1mx/Ic6nhDs=',
        ];

        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';

        $options->appId = $config['ali_app_id'];

        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = $config['ali_merchant_private_key'];  //应用私钥
 
        // $options->alipayCertPath = '';       //支付宝公钥证书文件路径
        // $options->alipayRootCertPath = '';   //支付宝根证书文件路径
        // $options->merchantCertPath = '';     //应用公钥证书文件路径

        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        $options->alipayPublicKey = $config['ali_alipay_public_key'];

        //可设置异步通知接收服务地址（可选）
        // $options->notifyUrl = '';

        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        $options->encryptKey = "";

        return $options;
    }
}
